﻿using DemoTG;
using Microsoft.VisualStudio.OLE.Interop;
using Newtonsoft.Json;
using SolidEdgeConstants;
using SolidEdgeFramework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TGComacAddin.View
{
    /// <summary>
    /// 一个树节点
    /// </summary>

    public class TreeNode
    {
        public string DisplayName
        {
            get
            {
                string _displayName = NodeName;
                if(!string.IsNullOrEmpty(Key))
                {
                    if(!string.IsNullOrEmpty(Value))
                    {
                        _displayName = $"'{Key}'={Value}";
                    }
                    else
                    {
                        _displayName = Key;
                    }
                }

                return _displayName;
            }
        }

        [JsonProperty("nodeName")]
        public string NodeName { get; set; }

        [JsonProperty("key")]
        public string Key { get; set; }

        [JsonProperty("value")]
        public string Value { get; set; }

        [JsonProperty("valueType")]
        public int ValueType { get; set; }

        [JsonProperty("childNodes")]
        public List<TreeNode> Children { get; set; }
        public TreeNode()
        {
            Children = new List<TreeNode>();
        }

        public TreeNode(string nodeName)
        {
            NodeName = nodeName;
            Children = new List<TreeNode>();
        }

        public TreeNode AddChild(string childName, string value)
        {
            var child = new TreeNode
            {
                Key = childName,
                Value = value
            };
            Children.Add(child);
            return child;
        }
    }

    /// <summary>
    /// TGEdgeBarView.xaml 的交互逻辑
    /// </summary>
    public partial class TGEdgeBarView : Page
    {
        // 消息线程，持续接受消息
        public System.Threading.Thread MsgThread = null;  

        // 记录控件
        internal static TGEdgeBarView S_MainView;

        // 树节点列表,用于做为数据源绑定
        private List<TreeNode> _treeNodeList;

        // 树根节点
        private TreeNode _treeRoot;

        // 当前打开的文档
        private SolidEdgeFramework.SolidEdgeDocument _doc;

        // 根应用程序接口
        private SolidEdgeFramework.Application _seapp;

        private IStorage  _rootStg=null;
        private IStorage _rootSubStg = null;

        void   ShowMessage(string msg)
        {
            tbInfo.Text = msg;
        }
        
        internal TGEdgeBarView(SolidEdgeFramework.SolidEdgeDocument doc)
        {
            _doc = doc;
            _seapp = doc.Application;
            InitializeComponent();
            UpdateTreeview();
            UpdateSurfaceInfo();
            S_MainView = this;
          
        }


        // 更新附着于曲面的信息
        public void UpdateSurfaceInfo()
        {
            bool hasAttachSurfaceInfo = UpdateSurfaceInfo(ref SurfaceDict);
            string msgStr = "当前文档无附着于曲面的信息";
            if (hasAttachSurfaceInfo)
            {
                msgStr = string.Format("当前文档中含附着于面的信息{0}条", SurfaceDict.Count);
            }

            ShowMessage(msgStr);
            btnQuerySurfaceInfo.IsEnabled = hasAttachSurfaceInfo;
        }

        // 更新文档结构树视图
        public void UpdateTreeview()
        {
            ConstructTree(out _treeRoot, _doc);
            _treeNodeList = new List<TreeNode>();
            _treeNodeList.Add(_treeRoot);
            treeViewPlyModel.ItemsSource = _treeNodeList;
        }


        // 更新曲面信息
        public Dictionary<int, SurfaceInfo> SurfaceDict; 
     

        /// <summary>
        /// 更新曲面信息
        /// </summary>
        /// <param name="surfDict"></param>
        /// <returns>只当文档中存在附着于曲线上的信息时返回true</returns>
        public bool UpdateSurfaceInfo(ref Dictionary<int, SurfaceInfo> surfDict)
        {
            if (!ReadSurfaceDataFromDoc(out List<SurfaceInfo> surfList, _doc))
                return false;

            if (surfList.Count == 0)
                return false;

            if(null==surfDict)
            {
                surfDict = new Dictionary<int, SurfaceInfo>();
            }
            foreach (var item in surfList)
            {
                surfDict[item.SurfaceID]   = item;               
            }

            return true;
        }


        private string _rootStgName = "TGDemo.Comac";

        /// <summary>
        /// 从文档中读取附着于文档的自定义数据PlyModel
        /// </summary>
        /// <param name="plyModel"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private bool ReadDataFromDoc(ref IStorage pStg,ref IStorage pRootSubStg,out PlyModel plyModel, in SolidEdgeFramework.SolidEdgeDocument doc)
        {
            string _streamName = "PropTest";
            plyModel = new PlyModel("");
            IBinaryData info = plyModel as IBinaryData;
            TGPropReadWrite pRW = new TGPropReadWrite(_rootStgName, _streamName);
            bool rt = pRW.ReadDataFromDoc(ref pStg, ref pRootSubStg,doc as SolidEdgeDocument, ref info);

            return rt;
        }

        private bool ReadDataFromDoc(out string data, ref IStorage pStg, ref IStorage pRootSubStg, in SolidEdgeFramework.SolidEdgeDocument doc)
        {
            string stgName = "ComacTree";
            string _streamName = "Detail";
            TGPropReadWrite pRW = new TGPropReadWrite(stgName, _streamName);
            bool rt = pRW.ReadDataFromDoc(out  data,ref pStg,  doc as SolidEdgeDocument);
            return rt;
        }


        /// <summary>
        /// 从文档中读取附着于曲线的信息
        /// </summary>
        /// <param name="surfaceList"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private bool ReadSurfaceDataFromDoc(out List<SurfaceInfo> surfaceList, in SolidEdgeFramework.SolidEdgeDocument doc)
        {
            surfaceList = new List<SurfaceInfo>();
            TGPropReadWrite pRW = new TGPropReadWrite(_rootStgName, "");
            bool rt = pRW.ReadCurveDataFromDoc<SurfaceInfo>(ref _rootStg,ref _rootSubStg, doc,ref surfaceList);
            return rt;
        }

        /// <summary>
        /// 根据文档构建树节点
        /// </summary>
        /// <param name="root"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private void ConstructTree(out TreeNode root, in SolidEdgeFramework.SolidEdgeDocument doc)
        {
            bool isComacFile = ReadDataFromDoc(out string data, ref _rootStg, ref _rootSubStg, doc);
            root = Newtonsoft.Json.JsonConvert.DeserializeObject<TreeNode>(data);
            int iii = 0;
        }

      


        private void btnQuerySurfaceInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (SurfaceDict == null)
                {
                    tbInfo.Text = "无附着于曲面的信息";
                    return;
                }

                tbInfo.Text = "请单击一个面";
                _seapp.AbortCommand(true);
                SolidEdgeFramework.Command cmd = _seapp.CreateCommand((int)seCmdFlag.seNoDeactivate);
                SolidEdgeFramework.ISEMouseEx mouse = cmd.Mouse as SolidEdgeFramework.ISEMouseEx;
                TGShowSurfaceInfo cmdShowSurfInfo = new TGShowSurfaceInfo(mouse, cmd,_doc, this);
                cmd.Start();
            }
            catch(Exception )
            {
               
            }
        }
    }
}
